from pathlib import Path
from PIL import Image
import pytesseract

def image_to_text(image_path):
    """
    从图片中提取文字
    
    Args:
        image_path (str): 图片文件路径
        
    Returns:
        str: 提取到的文本内容。如果处理失败则返回空字符串
    """
    try:
        # 确保文件存在
        image_path = Path(image_path)
        if not image_path.exists():
            print(f"错误：图片文件 '{image_path}' 不存在")
            return ""
            
        # 检查文件后缀
        valid_extensions = {".png", ".jpg", ".jpeg", ".bmp", ".tiff"}
        if image_path.suffix.lower() not in valid_extensions:
            print(f"错误：不支持的图片格式 '{image_path.suffix}'")
            print(f"支持的格式：{', '.join(valid_extensions)}")
            return ""
        
        # 打开并处理图片
        with Image.open(image_path) as img:
            # 使用pytesseract进行文字识别
            text = pytesseract.image_to_string(img, lang='chi_sim+eng')
            return text.strip()
            
    except Exception as e:
        print(f"处理图片时出错：{str(e)}")
        return ""

def main():
    # 简单的命令行界面
    print("图片文字提取工具")
    print("-" * 20)
    
    while True:
        path = input("请输入图片文件路径（输入q退出）：").strip()
        if path.lower() == 'q':
            break
            
        if not path:
            print("请输入有效路径")
            continue
            
        text = image_to_text(path)
        if text:
            print("\n提取的文字内容：")
            print("-" * 20)
            print(text)
            print("-" * 20)
        print()

if __name__ == "__main__":
    main()